<?php
  //==============================================
  // HTTP Brain Server
  //============================================== 
  // GET
  // http://IPADDRESS/brain.php?id=1001&a0=0&a1=1&a2=2&a3=3&a4=4&a5=5
  //==============================================

//============================
function readCmd($id) 
//============================
{
  $file = 'brain-'.$id.'.cmd';
  
   if (file_exists($file)) 
   {
      $in  = fopen($file,"r");
      if($in)
	{
	  while (!feof($in))
	    {
	      $row  = fgets($in);
	      echo($row); // Control Command to Processing Module
	    }
	  fclose($in);
	}
      unlink($file); // Execute command once - delete file
   }
}
//============================
function logData($id) 
//============================
{
    global $s_year,$s_month,$s_day,$s_hour,$s_min,$s_sec;
    // Log analog values to file (frequency = heartbeat
    $file = 'brain-'.$id.'-'.$s_year.'-'.$s_month.'-'.$s_day.".log"; 
    $out = fopen($file, 'a');
    $data = $s_hour." ".$s_min." ".$s_sec;
    $data = $data."\n";
    fwrite($out, $data); 
    fclose($out);
}    
//============================
function nowData($id) 
//============================
{
	global $s_year,$s_month,$s_day,$s_hour,$s_min,$s_sec;
    // Save latest analog values with time stamp
    $file = 'brain-'.$id.".now"; 
    $out = fopen($file, 'w');
    $data = $s_year."\n";fwrite($out, $data); 
    $data = $s_month."\n";fwrite($out, $data); 
    $data = $s_day."\n";fwrite($out, $data); 
    $data = $s_hour."\n";fwrite($out, $data); 
    $data = $s_min."\n";fwrite($out, $data); 
    $data = $s_sec."\n";fwrite($out, $data); 
    fclose($out); 
}
//============================

// Declaration
//==========================

$id     = $_GET['id'];
$ard    = $_GET['ard'];
$ip     = $_GET['ip'];  // Local IP adress of Raspberry Pi
$hb     = $_GET['hb'];  // Heart Beat   millisec
$msg    = $_GET['msg']; // Message from RaspberryPi

$s_day    = date('d');
$s_month  = date('m');
$s_year   = date('Y');
$s_sec    = date('s');
$s_min    = date('i');
$s_hour   = date('H');

if($id > 999 && $id < 10000) // Valid client id
  {
    if($msg==10) // Somebody knocking
      {
    	echo("1 $id $id");
    	$now = date('Y m d H i s');
        $file = $id.'.ip'; 
        $out = fopen($file, 'w');
        fwrite($out, $ip); 
        fwrite($out, "  "); 
        fwrite($out, $now); 
        fclose($out); 
      }
    if($msg==11) // Heartbeat
      {
        $time = time();
        $now = date('Y m d H i s');
        $now_plus = date('Y m d H i s',strtotime('+10 seconds',$time));
        //echo ("Now:$now\n");
        //echo ("+10:$now_plus_10s\n");
        $file = $id.'.hb'; 
        $out = fopen($file, 'w');
        fwrite($out, $now_plus); 
        fclose($out); 
      }
    readCmd($id); // check if any command has been initated from user
  }
exit;
?>
